package com.xxx.springboot.util;

import org.apache.commons.lang3.StringUtils;

/**
 * 手机号、邮箱地址、身份证号码脱敏处理
 */
public class PrivacyUtil {
	
	private static final String OVERLAY = "****";
	private static final int START = 3;
	private static final int END = 7;
	
	/**
	 * 姓名： 李小民
	 */
	public static String maskName(String fullName){
		if (StringUtils.isEmpty(fullName)) {
			return "";
		}
        String name = StringUtils.left(fullName, 1);
        return StringUtils.rightPad(name, StringUtils.length(fullName), "*");
    }

	/**
	 * 手机号：139****0504
	 * @param mobileNo
	 * @return
	 */
	public static String maskMobile(String mobileNo) {
		if (StringUtils.isEmpty(mobileNo)) {
			return "";
		}
		return StringUtils.overlay(mobileNo, OVERLAY, START, END);
	}

	/**
	 * 邮箱账号： 1234****56@qq.com
	 * @param email
	 * @return
	 */
	public static String maskEmail(String email) {
		if (StringUtils.isEmpty(email)) {
			return "";
		}
		
		String at = "@";
		if (!email.contains(at)) {
			return email;
		}
		
		// 这里主要逻辑是需要保留邮箱的注册商 比如@qq.com
		int length = StringUtils.indexOf(email, at);
		String content = StringUtils.substring(email, 0, length);
		String mask = StringUtils.overlay(content, OVERLAY, START, END);
		return mask + StringUtils.substring(email, length);
	}

	/**
	 * 身份证打码操作 132****99308084911
	 * 
	 * @param idCard
	 * @return
	 */
	public static String maskIdCard(String idCard) {
		if (StringUtils.isEmpty(idCard)) {
			return "";
		}
		return StringUtils.overlay(idCard, "********", START+3, END);
	}
	
	/**
	 * 身份证打码操作 132****99308084911
	 * 
	 * @param idCard
	 * @return
	 */
	public static String maskIdNumber(String idNumber){
		if (StringUtils.isEmpty(idNumber)) {
			return "";
		}
        if (idNumber.length() == 15){
            idNumber = idNumber.replaceAll("(\\w{4})\\w*(\\w{3})", "$1********$2");
        }
        if (idNumber.length() == 18){
            idNumber = idNumber.replaceAll("(\\w{6})\\w*(\\w{4})", "$1********$2");
        }
        return idNumber;
    }
	
	public static void main(String[] args) {
		System.out.println(maskName("李晓敏"));
		System.out.println(maskName("李敏"));
		System.out.println(maskMobile("18602017642"));
		System.out.println(maskEmail("210303620@qq.com"));
		System.out.println(maskIdCard("131282199009100021"));
		System.out.println(maskIdNumber("131282199009110021"));
		System.out.println(maskIdNumber("131219900912002"));
		
	}
}
